<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\Factory\Mysql\GrabGarbage AS FactoryGrabGarbage;       //电厂数据模型
use App\Models\Local\GrabGarbage AS LocalGrabGarbage;   //总部数据模型
use ErrorException;
use Log;

/**
 * 从电厂获取抓斗数据并保存到本地
 */
class GrabGarbageJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $timeout = 80; //队列超时时间
    protected $date;
    protected $factory_conn; //电厂连接
    protected $local_conn; //本地连接
    protected $factory_data_table; //本地保存的原始数据集合
    protected $local_data_table; //本地保存的格式化后的数据集合
    public $tries = 3;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($params=null)
    {
        $this->date = $params && isset($params['date']) ? $params['date'] : '';
        $this->factory_conn = $params && isset($params['factory_conn']) ? $params['factory_conn'] : '';
        $this->local_conn = $params && isset($params['local_conn']) ? $params['local_conn'] : '';
        $this->factory_data_table = $params && isset($params['factory_data_table']) ? $params['factory_data_table'] : '';
        $this->local_data_table = $params && isset($params['local_data_table']) ? $params['local_data_table'] : '';
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $this->saveData();
    }

    protected function saveData(){
        try{
            $factoryGrabGarbage = (new FactoryGrabGarbage())->setConnection($this->factory_conn)->setTable($this->factory_data_table);  //连接电厂内部数据库
            $localGrabGarbage = (new LocalGrabGarbage())->setConnection($this->local_conn)->setTable($this->local_data_table);      //连接本地数据库表
        
            $latest_row = $localGrabGarbage->findLatestReport();
            if($latest_row){
                $timestamp = $latest_row->time;
            }
            else{
                $timestamp = time() - 365 * 24 * 60 * 60;
            }

            $factoryGrabGarbage->select(['*'])
                ->where('time', '>=',$timestamp)
                ->chunk(100, function ($rows) use ($localGrabGarbage) {

                $params = [];
                if($rows && count($rows) > 0){
                    foreach ($rows as $key => $item) {
                        $local_row = $localGrabGarbage->findRowBySn($item->sn);
                        if(!$local_row){
                            //本地不存在则插入
                            $params[] = array(
                                'id' => $item->id,
                                'allsn' => $item->allsn,
                                'sn'=> $item->sn,
                                'time'=> $item->time,
                                'che'=> $item->che,
                                'dou'=> $item->dou,
                                'liao'=> $item->liao,
                                'code'=> $item->code,
                                'lost'=> $item->lost,
                                'hev'=> $item->hev,
                                'flag'=> 0,
                                'created_at' => date('Y-m-d H:i:s', $item->time),
                                'updated_at' => date('Y-m-d H:i:s')
                            );
                        }
                    }
                }

                if($params && count($params) > 0){
                    $localGrabGarbage->insertMany($params);
                    Log::info($this->date . '抓斗数据库数据插入本地成功'.count($params).'条');
                }
                else{
                    Log::info($this->date . '抓斗数据库没有数据插入');
                }
            });
        }
        catch(ErrorException $ex){
            Log::info('连接电厂数据库异常');
            Log::info(var_export($ex, true));
        }
    }
}
